package cn.iune.platform.dictionary;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;


@Transactional
@Service
public class TradeInfoServiceImpl implements ITradeInfoService {

	@Autowired
	private ITradeInfoDao dao;
	
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#getByID(java.lang.String)
	 */
	@Override
	public TradeInfo getByID(String fID) {
		return dao.getByID(fID);
	}

	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#getAll()
	 */
	@Override
	public List<TradeInfo> getAll(){
		return dao.getAll();
	}
	
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#getRoots(java.lang.String)
	 */
	@Override
	public List<TradeInfo> getRoots(String provider){
		return dao.getRoots(provider);
	}

	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#getChilds(java.lang.String)
	 */
	@Override
	public List<TradeInfo> getChilds(String fParent) {
		return dao.getChilds(fParent);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}

	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
				
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			TradeInfo obj = JSON.toJavaObject(javaObject, TradeInfo.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				//由于前端已经将删除的子节点放进删除缓冲区，所以无需下面这段代码特殊处理
				/*
				//删除树形子节点
				List<TradeInfo> objs = this.getChildren(obj.getfID());
				for(TradeInfo o :objs){
					dao.delete(o.getfID());
				}
				*/
				//删除自身
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				TradeInfo objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("code", 0);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}



	
	
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#getRootIDs(java.lang.String)
	 */
	@Override
	public List<String> getRootIDs(String provider) {
		// TODO Auto-generated method stub
		List<String> ids = new ArrayList<String>();
		List<TradeInfo> objs = dao.getRoots(provider);
		for(TradeInfo obj : objs){
			ids.add(obj.getfID());
		}
		return ids;
	}

	
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#getChildIDs(java.lang.String)
	 */
	@Override
	public List<String> getChildIDs(String fParent) {
		// TODO Auto-generated method stub
		List<String> ids = new ArrayList<String>();
		List<TradeInfo> objs = dao.getChilds(fParent);
		for(TradeInfo obj : objs){
			ids.add(obj.getfID());
		}
		return ids;
	}

	//获取ids
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#getIDsByParent(java.lang.String, java.lang.String)
	 */
	@Override
	public List<String> getIDsByParent(String fParent, String provider){
		if (fParent!=null && !fParent.equals("")){
			return this.getChildIDs(fParent);
		}else{
			return this.getRootIDs(provider);
		}
	}

	//更新sortNo
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#updateSortNo(com.iune.platform.backstage.TradeInfo, java.lang.String)
	 */
	@Transactional
	@Override
	public int updateSortNo(TradeInfo fs,String sortNo) {
		fs.setSortNo(sortNo);
		dao.update(fs);
		return 0;
	}
	
	//排序
	/* (non-Javadoc)
	 * @see com.iune.platform.backstage.ITradeInfoService#sortGroupInfo(java.lang.String, java.util.List)
	 */
	@Transactional
	@Override
	public int sortGroupInfo(String parentID,List<String> ids/*,List<Integer> versions*/){
		//彻底重新排序
		
		//首先获取父级排序号
		String fParent = parentID;
		String sortNoParent = "";
		if (fParent!=null && !fParent.equals("")){
			TradeInfo groupInfo = dao.getByID(fParent);//new TradeInfo(fParent);
			sortNoParent = groupInfo.getSortNo();
		}
		
		//获取传入的新排序的列表
		int index = 0;
		for(Iterator<String> i = ids.iterator();i.hasNext();){
			String strID = (String)i.next();
			index++;
			//新编写排序号
			//System.out.println("ids."+strID);
			String sortNoChild = "/" + String.format("%03d", index);
			String sortNoNew = sortNoParent + sortNoChild;
			TradeInfo groupInfo = dao.getByID(strID);//new TradeInfo(strID);
			if (!sortNoNew.equals(groupInfo.getSortNo())){
				//需要更新新序号
				//System.out.println("序号不同，需写入数据库！");
				int updateResult = this.updateSortNo(groupInfo,sortNoNew);
				if (updateResult!=0){
					return -1;
				}
				
				//2、判断是否有下一级
				String nodeKind = groupInfo.getNodeKind();
				if (!"nkLeaf".equals(nodeKind)){
					//不是叶子，需要处理下一级（递归调用即可）
					//递归调用，处理下级。
					List<String> idsChild = this.getIDsByParent(strID,"");
//					List<Integer> versionsChild = groupInfo.getVersionsByParent(fParent);
//					TradeInfo groupInfoChild = new TradeInfo();
					updateResult = this.sortGroupInfo(strID,idsChild /*,versionsChild*/ );
					if (updateResult!=0){
						return -1;
					}
				}
			}
			//System.out.println("旧序号." + groupInfo.getSortNo());
			//System.out.println("新序号." + sortNoNew);
			
		}
		/*
		for(Iterator<Integer> i = versions.iterator();i.hasNext();){
			int iVersion = i.next();
			System.out.println("versions."+iVersion);
		}
		*/
		return 0;
	}

	@Override
	public List<TradeInfo> getChildren(String fParent) {
		// TODO Auto-generated method stub
		return dao.getChildren(fParent);
	}

	@Override
	public JSONObject newData(JSONObject param) {
		return dao.create(param);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		//System.out.println("fileFactoryCreate.param-->>"+param.toJSONString());
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			//删除树形子节点
			List<TradeInfo> objs = this.getChildren(id);
			for(TradeInfo o :objs){
				dao.delete(o.getfID());
			}
			
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	/*
	在@Transaction注解中定义noRollbackFor和RollbackFor指定某种异常是否回滚。 
	@Transactional(noRollbackFor=RuntimeException.class) 
	@Transactional(RollbackFor=Exception.class) 
	*/
	@Transactional
	@Override
	public JSONObject saveData(JSONObject param) {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		JSONObject data;
		try {
			data = this.save(param);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#queryJDBC(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public JSONObject queryData(JSONObject param){
		//在此层面（ServiceImpl）统一处理异常，此层面直接被controller调用，面对BizData
		
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

		
}
